<?php
class ControllerNewsletterSubscriber extends Controller {
    private $error = array();

    public function index() {
        $this->load->language('newsletter/subscriber'); 
        $this->document->title = $this->language->get('heading_title')  . ' - ' . $this->language->get('text_subscriber_title'); 
        
        $this->load->model('newsletter/subscriber'); 
        $this->getList();
    }

    private function getList() {        
        $limit = $this->config->get('config_admin_limit');        
        //$limit = $limit > 20 ? $limit : 50;

        $url_page = '';
        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
            $url_page = '&page=' . $page;
        } else {
            $page = 1;
        }
        
        $url_sort = '';
        if (isset($this->request->get['sort'])) {
            $sort = $this->request->get['sort'];
            $url_sort = '&sort=' .$sort;
        } else {
            $sort = 'email';
        }
        
        $url_order = '';
        if (isset($this->request->get['order'])) {
            $order = $this->request->get['order'];
            $url_order = '&order=' . $order;
        } else {
            $order = 'ASC';
            $url_order = '&order=' . $order;
        }
        
        $url_filter = '';
        if (isset($this->request->get['filter_email'])) {
            $filter_email = $this->request->get['filter_email'];
            $url_filter .= '&filter_email=' . $filter_email;  
        } else {
            $filter_email = NULL;
        }        
        
        if (isset($this->request->get['filter_name'])) {
            $filter_name = $this->request->get['filter_name'];
            $url_filter .= '&filter_name=' . $filter_name;  
        } else {
            $filter_name = NULL;
        }
        
        if (isset($this->request->get['filter_date'])) {
			$filter_date = $this->request->get['filter_date'];
            $url_filter .= '&filter_date=' . $filter_date; 
		} else {
			$filter_date = NULL;
		}
        
        $url = $url_filter . $url_sort . $url_order . $url_page;
        $this->data['insert'] = HTTPS_SERVER . 'index.php?route=newsletter/subscriber/insert' . $url . '&token=' . $this->session->data['token'];
        $this->data['delete'] = HTTPS_SERVER . 'index.php?route=newsletter/subscriber/delete' . $url . '&token=' . $this->session->data['token'];
		$this->data['update_cc'] = HTTPS_SERVER . 'index.php?route=newsletter/subscriber/update_cc' . '&token=' . $this->session->data['token'];
        $this->data['action'] = '';
        
        $data = array(
            'filter_email'  => $filter_email,
            'filter_name'   => $filter_name,
            'filter_date'   => $filter_date,            
            'sort'          => $sort,
            'order'         => $order,
            'start'         => $page,
            'limit'         => $limit  
        );
        $total = $this->model_newsletter_subscriber->getTotalItems($data);        
        $results = $this->model_newsletter_subscriber->getList($data);
        $this->data['list'] = array();        
        foreach($results as $result){           
            $this->data['list'][] = array(       
                'email'     => $result['email'],
                'date'      => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                'name'      => $result['name'],
                'action'    => HTTPS_SERVER . 'index.php?route=newsletter/subscriber/update&subscriber_id=' . $result['subscriber_id'] . $url . '&token=' . $this->session->data['token']
            );
        }

        $this->data['heading_title'] = $this->language->get('heading_title'); 
        $this->data['text_insert'] = $this->language->get('text_insert');
        $this->data['text_delete'] = $this->language->get('text_delete');
        $this->data['text_edit'] = $this->language->get('text_edit');
        $this->data['text_email'] = $this->language->get('text_email');
        $this->data['text_name'] = $this->language->get('text_name');
        $this->data['text_date'] = $this->language->get('text_date');
        $this->data['text_empty'] = $this->language->get('text_empty');           
        $this->data['text_subscriber_title'] = $this->language->get('text_subscriber_title'); 
        $this->data['token'] = $this->session->data['token'];
        $this->data['filter'] = false;
        $this->data['button_filter'] = $this->language->get('button_filter');
        
        unset($this->data['success']);
        unset($this->data['error_warning']);
        
        $this->data['error_warning'] = isset($this->error['warning']) ? $this->error['warning'] : '';        
        if(isset($this->session->data['success'])){
            $this->data['success'] = $this->session->data['success'];
            unset($this->session->data['success']);
        } 
        else{
            $this->data['success'] = '';
        }
        
        $url = $url_filter . $url_sort . $url_order;        
        $pagination = new Pagination();
        $pagination->total = $total;
        $pagination->page = $page;
        $pagination->limit = $limit;
        $pagination->url = HTTPS_SERVER . 'index.php?route=newsletter/subscriber' . $url . '&page={page}&token=' . $this->session->data['token'];
        $this->data['pagination'] = $pagination->render();
        
        $url_order_change = $order == 'ASC' ? '&order=DESC' : '&order=ASC';
        $url = $url_filter . $url_order_change . $url_page;
        $this->data['sort_email'] = HTTPS_SERVER . 'index.php?route=newsletter/subscriber&sort=email' . $url . '&token=' . $this->session->data['token'];
        $this->data['sort_name'] = HTTPS_SERVER . 'index.php?route=newsletter/subscriber&sort=name' . $url . '&token=' . $this->session->data['token'];
        $this->data['sort_date'] = HTTPS_SERVER . 'index.php?route=newsletter/subscriber&sort=date_added' . $url . '&token=' . $this->session->data['token'];
          
        $this->data['sort'] = $sort;
        $this->data['order'] = $order;
        $this->data['filter_email'] = $filter_email;
         $this->data['filter_name'] = $filter_name;
        $this->data['filter_date'] = $filter_date;        
        $this->data['base_url'] = 'index.php?route=newsletter/subscriber';
        
        $this->template = 'newsletter/subscriber_list.tpl';
        $this->children = array(
            'common/header',
            'common/footer'
        );

        $this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
    }
      
    public function delete() {
        $this->load->language('newsletter/subscriber'); 
        $this->document->title = $this->language->get('heading_title');

        $this->load->model('newsletter/subscriber');   
        if(isset($this->request->post['selected']) && ($this->validateDelete())){
            foreach ($this->request->post['selected'] as $email) {
                $this->model_newsletter_subscriber->delete($email);
            }

            $this->session->data['success'] = $this->language->get('text_delete_success');

            $url = '';
            if (isset($this->request->get['page'])) {
                $url .= '&page=' . $this->request->get['page'];
            }                

            $this->redirect(HTTPS_SERVER . 'index.php?route=newsletter/subscriber&token=' . $this->session->data['token'] . $url);
        }

        $this->getList();
    }
    
    private function validateDelete() {
        if(!$this->user->hasPermission('modify', 'newsletter/subscriber')){
            $this->error['warning'] = $this->language->get('error_permission');
        }

        if (!$this->error){
            return TRUE;
        } 
        else{
            return FALSE;
        }
    }       

    private function getUrl(){
        $url = '';
        
        if (isset($this->request->get['sort'])) {            
            $url = '&sort=' . $this->request->get['sort'];
        } 
        
        if (isset($this->request->get['order'])) {            
            $url = '&order=' . $this->request->get['order'];
        }         

        $url_filter = '';
        if (isset($this->request->get['filter_email'])) {            
            $url_filter .= '&filter_email=' . $this->request->get['filter_email'];
        }        
        if (isset($this->request->get['filter_name'])) {          
            $url .= '&filter_name=' . $this->request->get['filter_name'];
        } 
        if (isset($this->request->get['filter_date'])) {
            $url .= '&filter_date=' . $this->request->get['filter_date'];
		} 
        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }
        
        return $url;
    }
    
    public function insert() {
        $this->load->language('newsletter/subscriber'); 
        //$this->document->title = $this->language->get('heading_title');

        $url = $this->getUrl();
        
        $this->load->model('newsletter/subscriber');    
        if(($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()){
            if(!$this->model_newsletter_subscriber->subscriberExists($this->request->post['email'])){
                $this->model_newsletter_subscriber->insertSubscriber($this->request->post);            
                $this->session->data['success'] = $this->language->get('text_success');

                $data = array(
                    'email'	=> $this->request->post['email'],
                    'name'	=> $this->request->post['name']
                );
                $this->subscriberCC($data);

                $this->redirect(HTTPS_SERVER . 'index.php?route=newsletter/subscriber' . $url . '&token=' . $this->session->data['token']);
            }
            else{
                $this->error['email'] = $this->language->get('error_exists');        
            }
        }
        
        $this->getForm();
    }
    
    public function update() {
        $this->load->language('newsletter/subscriber'); 
        //$this->document->title = $this->language->get('heading_title');

        $url = $this->getUrl();        
        
        $this->load->model('newsletter/subscriber');    
        if(($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()){
            $subscriber_id = isset($this->request->get['subscriber_id']) ? $this->request->get['subscriber_id'] : '';            
            $this->model_newsletter_subscriber->editSubscriber($subscriber_id, $this->request->post);            
            $this->session->data['success'] = $this->language->get('text_edit_success');
            
            $this->redirect(HTTPS_SERVER . 'index.php?route=newsletter/subscriber' . $url . '&token=' . $this->session->data['token']);            
        }        
        
        $this->getForm();
    }
      
    public function getForm(){
        $this->document->title = $this->language->get('heading_title')  . ' - ' . $this->language->get('text_title_edit');

        $this->data['heading_title'] = $this->language->get('heading_title');
        $this->data['form_title'] = $this->language->get('text_title_edit');
        $this->data['text_save'] = $this->language->get('text_save');
        $this->data['text_cancel'] = $this->language->get('text_cancel');
        $this->data['text_email'] = $this->language->get('text_email');
        $this->data['text_name'] = $this->language->get('text_name');
        $this->data['text_date'] = $this->language->get('text_date');           
        $this->data['token'] = $this->session->data['token'];        
        
        $url = $this->getUrl();
        
        $subscriber_id = isset($this->request->get['subscriber_id']) ? $this->request->get['subscriber_id'] : 0;
        $this->load->model('newsletter/subscriber');            
        $subscriber = $this->model_newsletter_subscriber->getSubscriber($subscriber_id);
        
        if($subscriber_id){
            $this->data['action'] = HTTPS_SERVER . 'index.php?route=newsletter/subscriber/update&subscriber_id=' . $subscriber_id .  $url . '&token=' . $this->session->data['token'];
        }
        else{
            $this->data['action'] = HTTPS_SERVER . 'index.php?route=newsletter/subscriber/insert' .  $url . '&token=' . $this->session->data['token'];   
        }
        $this->data['cancel'] = HTTPS_SERVER . 'index.php?route=newsletter/subscriber' .  $url . '&token=' . $this->session->data['token'];

        if(isset($this->request->post['email'])){
            $this->data['email'] = $this->request->post['email'];    
        }
        elseif(isset($subscriber['email'])){
            $this->data['email'] = $subscriber['email'];   
        }
        else{
            $this->data['email'] =  '';
        }
        
        if(isset($this->request->post['name'])){
            $this->data['name'] = $this->request->post['name'];    
        }
        elseif(isset($subscriber['name'])){
            $this->data['name'] = $subscriber['name'];   
        }
        else{
            $this->data['name'] =  '';
        }
        
        if(isset($this->request->post['date'])){
            $this->data['date'] = date($this->language->get('date_format_short'), strtotime($this->request->post['date']));    
        }
        elseif(isset($subscriber['date'])){
            $this->data['date'] = date($this->language->get('date_format_short'), strtotime($subscriber['date']));
        }
        else{
            $this->data['date'] =  date($this->language->get('date_format_short'));
        }
        
        unset($this->data['error']);
        if(isset($this->error['email'])){
            $this->data['error'] = $this->error['email'];        
        }        
        if(isset($this->error['name']) && !isset($this->data['error'])){
            $this->data['error'] = $this->error['name'];        
        }        
        
        $this->template = 'newsletter/subscriber_form.tpl';
        $this->children = array(
            'common/header',
            'common/footer'
        );

        $this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
    }

    
    private function validateForm() {
        if (!$this->user->hasPermission('modify', 'newsletter/subscriber')) {
            $this->error['warning'] = $this->language->get('error_permission');
        }

        //$pattern = '/^[A-Z0-9._%-+]+@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z]{2,6}$/i';
        $pattern = "/^([a-zA-Z0-9])+([a-zA-Z0-9+\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/";
        if(!isset($this->request->post['email']) || !preg_match($pattern, $this->request->post['email'])){
            $this->error['email'] = $this->language->get('error_email');
        }
        
        if(!isset($this->request->post['name']) || strlen(utf8_decode($this->request->post['name'])) == 0){
            $this->error['name'] = $this->language->get('error_name');
        }
        
        if(!$this->error){
            return TRUE;
        } 
        else{
            return FALSE;
        }
    }

	public function update_cc(){
		if(!$this->user->hasPermission('modify', 'newsletter/subscriber')){
            echo  $this->language->get('error_permission');
			return;
        }

		$resultString = 'Data has been update to ConstantContact';

		// Use API to add data to ConstantContact newsletter system
        $requirePath = str_replace('admin', 'newsletter/constantcontact', DIR_APPLICATION);
        /*
        require_once($requirePath . 'cc_class.php');
        $ccContact = new CC_Contact();
        // Get all available lists for the current CC account.
        $contactListsCC = $ccContact->getSubscribers();

        // Get contact lists
        $contactList = array();
        //while($contactListsCC['next'] != ''){
            foreach($contactListsCC['items'] as $item){
                if($item['status'] == 'Active'){
                    $contactList[] = $item['EmailAddress'];
                }
            }
            //$contactListsCC = $ccContact->getSubscribers();
        //}
		$critical = "'" . implode("', '", $contactList) . "'";
        var_dump($contactListsCC);
        */
        $critical = '';
        // Load data from database
		$this->load->model('newsletter/subscriber');
		$data = $this->model_newsletter_subscriber->getListForCC($critical, 'email');
        //$data = $this->model_newsletter_subscriber->getListEmptyName('email');

        // Write data from database to text file
		//$handle = @fopen(dirname(__FILE__) . '/subscribers.txt', "w");
        $handle = @fopen($requirePath . '/subscribers.txt', "w");
        //fwrite($handle, "Email Address\tFirst Name\tLast Name\n");
		fwrite($handle, '"Email Address","First Name","Last Name"' . "\n");
		foreach($data as $item){
            if(trim($item["name"]) != ''){
                $name = explode(' ', $item["name"]);
                //$firstName = trim($name[0]);
                $firstName = '"' . trim($name[0]) . '"';
                unset($name[0]);
                //$lastName = trim(implode(' ', $name));
                $lastName = trim(implode(' ', $name));
                $lastName = $lastName ? '"' . $lastName . '"' : '';
            }
            else{
                $firstName = '';
                $lastName = '';
            }

			//fwrite($handle, $item["email"] . "\t" . $firstName . "\t" . $lastName . "\n");
            fwrite($handle, '"' . $item["email"] . '",' . $firstName . ',' . $lastName . "\n");
		}
		fclose($handle);

        header('Content-type: text/plain');
        header('Content-Disposition: attachment; filename="subscribers.txt"');
        @readfile($requirePath . 'subscribers.txt');

        //$this->redirect(HTTP_CATALOG . 'newsletter/constantcontact/?file=subscribers');
        $this->redirect(HTTPS_SERVER . 'index.php?route=newsletter/subscriber&token=' . $this->session->data['token']);
	}

    public function subscriberCC($data) {
        // Use API to add data to ConstantContact newsletter system
        require_once(str_replace('admin', 'newsletter/constantcontact', DIR_APPLICATION) . 'cc_class.php');
        $ccContact = new CC_Contact();
        $ccList = new CC_List();
        // Get all available lists for the current CC account.
        $allLists = $ccList->getLists();
        // Fill all for the contact.
        $postFields = array();
        $name = explode(' ', $data["name"]);
        $postFields["email_address"] = $data["email"];
        $postFields["first_name"] = trim($name[0]);
        unset($name[0]);
        $postFields["last_name"] = trim(implode(' ', $name));
        $postFields["middle_name"] = '';
        $postFields["home_number"] = '';
        $postFields["address_line_1"] = '';
        $postFields["address_line_2"] = '';
        $postFields["address_line_3"] = '';
        $postFields["city_name"] = '';
        $postFields["state_code"] = '';
        $postFields["state_name"] = '';
        $postFields["country_code"] = '';
        $postFields["zip_code"] = '';
        $postFields["sub_zip_code"] = '';
        $postFields["mail_type"] = 'HTML';

        $group = array();
        foreach ($allLists as $k => $item) {
            $group[] = $item['id'];
        }
        $postFields["lists"] = $group;

        try{
            $contactXML = $ccContact->createContactXML(null, $postFields);
            $error = !$ccContact->addSubscriber($contactXML);
        }
        catch (Exception $e) {
            $error = "<span style='color:red;'>" . $e . "</span>";
        }
    }
}
?>